// db/userTable.js

const { DataTypes, sequelize } = require("../config/sequelizeCommon");

const checkTableExistsQuery = `
SELECT table_name
  FROM information_schema.tables
  WHERE table_schema = 'OrderingSystem' AND table_name = 'users'
`;
(async() => {
    try {
        const existingTables = sequelize.query(checkTableExistsQuery, {
            type: sequelize.QueryTypes.SELECT,
        });

        const User = sequelize.define("User", {
            id: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true,
            },
            account: {
                type: DataTypes.STRING(255),
                allowNull: false,
                unique: true,
                validate: {
                    is: /^[\w\.-]+@[a-zA-Z\d\.-]+\.[a-zA-Z]{2,}$|^1[3456789]\d{9}$/,
                },
            },
            password: {
                type: DataTypes.STRING(255),
                allowNull: false,
                validate: {
                    isStrongPassword: function(value) {
                        if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}/.test(value)) {
                            throw new Error(
                                "Password must contain at least 8 characters with a combination of uppercase and lowercase letters and numbers."
                            );
                        }
                    },
                },
            },
        });

        if (existingTables.length === 0) {
            // 表不存在，创建表
            User.sync();
        }
        //return User;
        module.exports = { User };
        //return User;
    } catch (error) {
        console.error("Error checking or creating user table:", error);
    }
})();